/**
 * 作者: sessionliang
 * 时间: 2017-08-20
 * 描述: 预约考试详情页面
 */
define(function(require, exports, module) {
	"use strict";
	//每一个页面都要引入的工具类
	var CommonTools = require('CommonTools_Core');
	var WindowTools = require('WindowTools_Core');
	//轮播图工具类
	var GallerySliderTools = require('GallerySliderTools_Core');

	//base service
	var baseService = require('Base_Service');
	var studyLogsService = require('StudyLogs_Service');
	var enumHelper = require('Common_Enum');

	var model = null;
	var data;
	var dtPicker;
	
	var uploadTimeStyle = '';
	var uploadDate = '';
	var uploadHours = [];

	//每一个页面都要引入的工具类
	// initready 要在所有变量初始化做完毕后
	CommonTools.initReady(initData);
	/**
	 * @description 初始化数据,结合initReady使用
	 * plus情况为plusready
	 * 其它情况为直接初始化
	 */
	function initData() {
		//引入必备文件,下拉刷新依赖于mui与mustache
		CommonTools.importFile([
			'js/libs/mui.min.js',
			'js/libs/mui.picker.min.js'
		], function() {
			initHomePage();
			initListeners();
		});
	}

	/**
	 * @description 监听
	 */
	function initListeners() {
		var studyTime = document.getElementById('studyTime');
		if(studyTime.selectedIndex >= 0){
			uploadTimeStyle = studyTime.options[studyTime.selectedIndex].value;
		}
		studyTime.addEventListener('change', function(e) { //时间变化需要跟新教练
			var val = this.options[this.selectedIndex].value;
			uploadTimeStyle = val;
			clearTime();
		});
		mui(".mui-content").on("tap", "#btn_time", function() {
			console.log('click');
			if(data != null) {
				dtPicker = new mui.DtPicker({
					type: "date",
					beginDate: new Date()
				});
				dtPicker.show(function(selectItems) {
					console.log(selectItems.text);
					uploadDate = selectItems.text;
					mui('#btn_time')[0].innerHTML = selectItems.text;
					updateTimeSelect(selectItems.text);
				});
			}
		});
		mui(".mui-content").on("tap", "#btn_edit", function() {
			console.log('click');
			var hours = document.getElementsByName('hours');
			var check_val = [];
			for(var key in hours) {
				if(hours[key].checked) {
					check_val.push(hours[key].value);
				}
			}
			uploadHours = check_val;
			if(data != null) {
				if(uploadDate==''){
					mui.toast("请选择日期")
					return;
				}
				if(uploadHours.length<=0){
					mui.toast("请选择小时")
					return;
				}
				var editData = {
					StudentLogID : data.StudyLogID,
					Date : uploadDate,
					TimeSoltType : uploadTimeStyle,
					Times : !!uploadHours ? uploadHours.join(",") : "",
					TimeArray : []
				}
				debugger;
				studyLogsService.edit(editData,function(){
					if(typeof(plus)!='undefined'){
						var opener = plus.webview.currentWebview().opener();
						opener.reload();
						WindowTools.closeCurrentPage();
					}
				})
			}
		});
	}
	
	/**
	 * 更新时间选择
	 */
	function updateTimeSelect(date) {
		if(typeof(plus) != 'undefined'){
			console.log('show loading');
			plus.nativeUI.showWaiting('加载中...');
		}
	
		var timeData = {
			'PlaceID': data.PlaceID,
			'TimeSoltType': uploadTimeStyle,
			'CourseType': data.CourseType,
			'CoachID': data.CoachID,
			'Date': date,
			'SubjectType': data.SubjectType,
			'DrivingID': data.DrivingID
		};
		debugger;
		studyLogsService.canusetime(timeData, function(res) {

			var totalHours = res.totalHours;
		
			var hourSelect = document.getElementById('hourSelect');
			var allItem = '';
			var total = 0;
			for(var i = res.startTime; i < res.endTime; i++) {
				if(!haveThisHour(res.usedTimes, i) || data.SubjectType == 'Simulate') {
					total = total + 1;
					allItem += '<div class="mui-input-row mui-checkbox"> ' +
						'<label>' + i + '点</label>' +
						'<input name="hours" value="' + i + '" type="checkbox" > </div> ';
				}
			}
			if(total==0){
				mui.toast('没有可用时间');
			}
			hourSelect.innerHTML = allItem;
		});
	}
	
	function haveThisHour(usedTimes, curTime) {
		for(var use = 0; use < usedTimes.length; use++) {
			if(usedTimes[use] == curTime) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @description 渲染頁面
	 */
	function initHomePage() {
		data = JSON.parse(WindowTools.getExtraDataByKey("data"));
		debugger;
		var record;
		if(data.IsRecord) {
			record = '已记录';
		} else {
			record = '未记录';
			if(data.CourseType=='Course2'||data.CourseType=='Course3'){
				document.getElementById('btn_time').style.display = '';
				document.getElementById('btn_edit').style.display = '';
				document.getElementById('study_time_title').style.display = '';
				document.getElementById('studyTime').style.display = '';
				document.getElementById('hourSelect_title').style.display = '';
				document.getElementById('hourSelect').style.display = '';
			}
		}
		mui('#school')[0].innerHTML = data.DrivingTitle;
		mui('#place')[0].innerHTML = data.PlaceName;
		mui('#course')[0].innerHTML = enumHelper.courseTypeFormat(data.CourseType);
		mui('#coach')[0].innerHTML = data.CoachName;
		mui('#date')[0].innerHTML = data.Times;
		mui('#port')[0].innerHTML = record;
	}

	function getTime(time) {
		if(time == null) {
			return 'N/A';
		} else {
			return time.replace("T", ' ');
		}
	}
	
	/**
	 * 清除时间选择
	 */
	function clearTime() {
		mui("#btn_time")[0].innerHTML = '选择日期';
		mui('#hourSelect')[0].innerHTML = '';
		uploadDate = '';
		uploadHours = [];
	}
});